<template>
  <div class="box">
    <header class="header">
      <van-nav-bar left-arrow @click-right="goSearch">
        <template #right>
          搜索
        </template>
        <template #title>
          <van-search v-model="value" shape="round" placeholder="请输入搜索关键词" />
        </template>
      </van-nav-bar>
    </header>
    <div class="content">
      <div class="hot-search s-box">
        <h4>热门搜索：</h4>
        <div class="list">
          <van-tag v-for="item in hot" :key="item" plain type="primary" size="large">{{item}}</van-tag>
        </div>
      </div>
      <div class="history-search s-box">
        <h4>搜索历史：</h4>
        <div class="list">
          <van-tag v-for="(item,idx) in history" :key="item.searchId" plain type="primary" closeable @close="close(item.searchId, idx)" size="large">{{item.searchText}}</van-tag>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Search, Tag } from 'vant'

import { getSearch, addSearch, delSearch } from '../../api/index.js'

Vue.use(NavBar)
Vue.use(Search)
Vue.use(Tag)

export default {
  data () {
    return {
      value: '',
      hot: ['手机', '电脑', '化妆品', '地铁睡觉神器', '李现同款手机', '华为P40', '苹果5G'],
      history: []
    }
  },
  methods: {
    close (id, i) {
      delSearch({
        userId: localStorage.getItem('userId'),
        searchId: id
      }).then(res => {
        console.log('删除搜索历史关键字成功')
        this.history.splice(i, 1)
      })
    },
    goSearch () {
      addSearch({
        userId: localStorage.getItem('userId'),
        searchText: this.value
      }).then(res => {
        // console.log('添加成功，可以跳转到搜索页面了')
        getSearch({
          userId: localStorage.getItem('userId')
        }).then(res => {
          this.history = res.data.data
          console.log(this.history)
        })
      })
      this.$router.push('/searchRes/' + this.value)
    }
  },
  mounted () {
    getSearch({
      userId: localStorage.getItem('userId')
    }).then(res => {
      this.history = res.data.data
      console.log(this.history)
    })
  }
}
</script>

<style lang="scss">
.van-nav-bar{
  border-bottom: solid 1px #aaa;
}
.van-nav-bar__title{
  width: 70%;
  max-width: 70%;
}
.van-search{
  padding: 0;
}
.content{
  padding: 0.1rem;
  background: #eee;
}
.s-box{
  padding: 0.1rem 0;
  h4{
    font-weight: normal;
    font-size: 18px;
  }
  .list{
    .van-tag{
      margin: 0.06rem;
      color: #777;
    }
  }
}
</style>
